/// 聊天应用入口文件
library;
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import 'package:chat_project/providers/auth_provider.dart';
import 'package:chat_project/providers/chat_provider.dart';
import 'package:chat_project/providers/user_provider.dart';
import 'package:chat_project/screens/splash_screen.dart';
import 'package:chat_project/screens/login_screen.dart';
import 'package:chat_project/screens/register_screen.dart';
import 'package:chat_project/screens/home_screen.dart';
import 'package:chat_project/screens/chat_screen.dart';
import 'package:chat_project/config/theme_config.dart';
import 'package:chat_project/config/api_config.dart';
import 'dart:io' show Platform;
import 'package:flutter/foundation.dart' show kIsWeb;

void main() {
  // 确保Flutter绑定初始化
  WidgetsFlutterBinding.ensureInitialized();
  
  // 检测平台，并根据平台提供适当的API配置
  if (kIsWeb) {
    // Web平台 - 使用局域网IP配置
    try {
      ApiConfig.configureForWeb('192.168.35.39');
      print('检测到Web平台，已配置API为局域网环境: ${ApiConfig.hostUrl}');
      print('Web API基础URL: ${ApiConfig.baseUrl}');
    } catch (e) {
      print('Web平台配置API地址时出错: $e');
    }
  } else {
    // 移动/桌面平台 - 可以配置为局域网地址
    try {
      // 确保使用局域网地址
      // ApiConfig.configureForLocalDevelopment();
      ApiConfig.configureForLAN('192.168.35.39');
      print('非Web平台：已配置API为局域网环境: ${ApiConfig.hostUrl}');
      print('API基础URL: ${ApiConfig.baseUrl}');
      print('API登录URL: ${ApiConfig.loginUrl}');
    } catch (e) {
      print('配置API地址时出错: $e');
    }
  }
  
  runApp(
    MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (_) => AuthProvider()),
        ChangeNotifierProvider(create: (_) => ChatProvider()),
        ChangeNotifierProvider(create: (_) => UserProvider()),
      ],
      child: const MyApp(),
    ),
  );
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  bool _initialized = false;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    
    // 只初始化一次
    if (!_initialized) {
      // 初始化AuthProvider
      final authProvider = Provider.of<AuthProvider>(context, listen: false);
      authProvider.init();
      
      // 初始化SocketService
      WidgetsBinding.instance.addPostFrameCallback((_) async {
        if (authProvider.isAuthenticated && authProvider.user != null) {
          final chatProvider = Provider.of<ChatProvider>(context, listen: false);
          await chatProvider.init(authProvider.user!);
        }
      });
      
      _initialized = true;
    }
  }

  @override
  Widget build(BuildContext context) {
    // 不使用listen:true的Provider避免重复构建
    final authProvider = Provider.of<AuthProvider>(context, listen: false);
    
    // 配置路由
    final router = GoRouter(
      initialLocation: '/',
      debugLogDiagnostics: true, // 启用路由诊断日志
      redirect: (context, state) {
        // 检查用户是否已登录，除了登录和注册页面外的其他页面都需要登录
        final isLoggedIn = authProvider.isAuthenticated;
        final isSplash = state.matchedLocation == '/';
        final isAuthPage = state.matchedLocation == '/login' || state.matchedLocation == '/register';
        
        print('路由重定向检查: 路径=${state.matchedLocation}, 已登录=$isLoggedIn, 是闪屏=$isSplash, 是认证页=$isAuthPage');
        
        // 如果是闪屏页，不做重定向
        if (isSplash) return null;
        
        // 如果未登录且尝试访问非认证页面，重定向到登录页
        if (!isLoggedIn && !isAuthPage) {
          print('未登录访问受保护页面，重定向到登录页');
          return '/login';
        }
        
        // 如果已登录且尝试访问认证页面，重定向到主页
        if (isLoggedIn && isAuthPage) {
          print('已登录访问认证页面，重定向到主页');
          return '/home';
        }
        
        print('无需重定向');
        return null;
      },
      routes: [
        GoRoute(
          path: '/',
          builder: (context, state) => const SplashScreen(),
        ),
        GoRoute(
          path: '/login',
          builder: (context, state) => const LoginScreen(),
        ),
        GoRoute(
          path: '/register',
          builder: (context, state) => const RegisterScreen(),
        ),
        GoRoute(
          path: '/home',
          builder: (context, state) => const HomeScreen(),
        ),
        GoRoute(
          path: '/chat/:conversationId/:userId',
          builder: (context, state) {
            final conversationId = state.pathParameters['conversationId'] ?? '';
            final userIdParam = state.pathParameters['userId'] ?? '';
            
            print('路由参数(原始): conversationId=$conversationId, userId=$userIdParam');
            
            // 解码URL编码的参数
            String decodedUserId;
            try {
              decodedUserId = Uri.decodeComponent(userIdParam);
              print('URL解码后的userId: $decodedUserId');
            } catch (e) {
              print('URL解码失败: $e, 使用原始值');
              decodedUserId = userIdParam;
            }
            
            // 提取用户ID
            String userId = decodedUserId;
            if (decodedUserId.contains('{') || decodedUserId.contains('}') || decodedUserId.contains(':')) {
              // 尝试提取ID
              final idMatch = RegExp(r"_id:\s*([^\s,}]+)").firstMatch(decodedUserId);
              if (idMatch != null && idMatch.groupCount > 0) {
                userId = idMatch.group(1)!.trim();
                print('从路由参数提取出用户ID: $userId');
              }
            }
            
            // 处理其他特殊字符
            if (userId.contains('%')) {
              try {
                userId = Uri.decodeComponent(userId);
                print('二次解码用户ID: $userId');
              } catch (e) {
                print('二次解码失败: $e');
              }
            }
            
            print('最终使用的用户ID: $userId');
            
            return ChatScreen(
              conversationId: conversationId,
              userId: userId,
            );
          },
        ),
      ],
    );
    
    return MaterialApp.router(
      title: '聊天应用',
      theme: ThemeConfig.getThemeData(),
      routerConfig: router,
      debugShowCheckedModeBanner: false,
    );
  }
}
